# re 正则

import re

# split
some_text = 'alpha, beta,,,,gamma delta'
arr = re.split('[,]+', some_text)
print(arr)  # ['alpha', ' beta', 'gamma delta']

# maxsplit 最大拆分的次数
arr = re.split('[,]+', some_text, maxsplit=2)
print(arr)  # ['alpha', ' beta', 'gamma delta']

arr = re.split('[,]+', some_text, maxsplit=1)
print(arr)  # ['alpha', ' beta,,,,gamma delta']

# findall
pat = '[a-zA-Z]+'
text = '"Hm... Err -- are you sure?" he said, sounding insecure.'
arr = re.findall(pat, text)
print(arr)  # ['Hm', 'Err', 'are', 'you', 'sure', 'he', 'said', 'sounding', 'insecure']

pat = r'[.?\-",]+'
arr = re.findall(pat, text)
print(arr)  # ['"', '...', '--', '?"', ',', '.']

# sub
pat = '{name}'
text = 'Dear {name}...'
new_str = re.sub(pat, 'newValue', text)
print(new_str)  # Dear newValue...

# escape 转移成正则
pat = re.escape('www.python.org')
print(pat)  # www\.python\.org
pat = re.escape('But where is the ambiguity?')
print(pat)  # But\ where\ is\ the\ ambiguity\?

# 编组 0组是整个字符串
text = 'There (was a (wee) (cooper)) who (lived in Fyfe)'
# 0 There was a wee cooper who lived in Fyfe
# 1 was a wee cooper
# 2 wee
# 3 cooper
# 4 lived in Fyfe


m = re.match(r'www\.(.*)\..{3}', 'www.python.org')
print(m.group(0))  # www.python.org
print(m.group(1))  # python

# 第一组的开始匹配位置和结束位置
print(m.start(1))  # 4
print(m.end(1))  # 10
print(m.span(1))  # (4, 10)

# 替换编组 \1
emphasis_pattern = r'\*([^\*]+)\*'
text = re.sub(emphasis_pattern, r'<em>\1</em>', 'Hello, *world*!')
print(text)

# 贪婪匹配
emphasis_pattern = r'\*(.+)\*'
text = re.sub(emphasis_pattern, r'<em>\1</em>', '*This* is *it*!')
# 把 This* is *it 包裹起来了
print(text)  # <em>This* is *it</em>!

# 非贪婪匹配
emphasis_pattern = r'\*(.+?)\*'
text = re.sub(emphasis_pattern, r'<em>\1</em>', '*This* is *it*!')
print(text)  # <em>This</em> is <em>it</em>!

